package com.hht.baselibs.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

typealias OnItemClickListener<T> = (T) -> Unit

/**
 * Author:chen'hu
 * Time:2024/3/19 17:08
 * Description:This is CommonAdapter
 */
open class BaseDataAdapter<T>(
    private val layoutResId: Int,
    private val bindHolder: (View, T) -> Unit,
) : RecyclerView.Adapter<BaseDataAdapter<T>.CommonViewHolder>() {

    private var onItemOnClickListener: OnItemClickListener<T>? = null

    fun setOnItemOnClickListener(listener: OnItemClickListener<T>): BaseDataAdapter<T> {
        this.onItemOnClickListener = listener
        return this
    }

    private var itemList: List<T> = emptyList()

    fun setAdapterData(list: List<T>): BaseDataAdapter<T> {
        this.itemList = list
        notifyDataSetChanged()
        return this
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
        return CommonViewHolder(view)
    }

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
        bindHolder(holder.itemView, itemList[position])
        onItemOnClickListener?.let { listener ->
            holder.itemView.setOnClickListener {
                listener.invoke(itemList[position])
            }
        }

    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    fun getItemList(): List<T> {
        return itemList
    }

    inner class CommonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}